package nil.ed.lazy.io.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @author lidelin
 * @since 1.0
 */
public class StreamUtils {

    /**
     * copy stream bytes to byte array
     * @param in source stream
     * @return a byte array which contains all bytes of stream
     * @throws IOException any io exp
     */
    public static byte[] copyToByteArray(InputStream in) throws IOException {
        if (in == null) {
            return new byte[0];
        } else {
            ByteArrayOutputStream out = new ByteArrayOutputStream(4096);
            copy(in, out);
            return out.toByteArray();
        }
    }

    /**
     * copy stream from src to target
     * copy from spring
     * @param src source stream
     * @param target target stream
     * @return copy bytes count
     * @throws IOException ang read or write exp
     */
    public static int copy(InputStream src, OutputStream target) throws IOException {
        int byteCount = 0;
        byte[] buffer = new byte[4096];

        int n;
        while ((n = src.read(buffer)) != -1) {
            target.write(buffer, 0, n);
            byteCount += n;
        }

        target.flush();
        return byteCount;
    }

    public static void closeQuietly(InputStream in) {
        try {
            if (in != null) {
                in.close();
            }
        } catch (IOException ignore) {
        }
    }

    public static void closeQuietly(OutputStream out) {
        try {
            if (out != null) {
                out.close();
            }
        } catch (IOException ignore) {
        }
    }

}
